package com.ruoyi.framework.config;

/**
 * Description:
 * Author: EDY
 * Date: 2023/8/1
 */

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;

/**
 * @descriptions: 打印完整sql
 * @author: obcy
 * @date: 2022/9/18 18:10
 * @version: 1.0
 */

/**
 * ClassName: ExecteSqlLogInterceptor 控制台打印完整sql，用于mybatisplus
 * Description: TODO
 * Date: 2022/1/14 11:09
 *
 * @author obcy
 * @version V1.0.0
 */
@Intercepts(
        {
                @Signature(type = Executor.class, method = "update", args = {
                        MappedStatement.class, Object.class }
                ),
                @Signature(type = Executor.class, method = "query", args = {
                        MappedStatement.class, Object.class, RowBounds.class,
                        ResultHandler.class })
        }
)
@Component
public class ExecteSqlLogInterceptor implements Interceptor {

    private static Logger daoLogger = LoggerFactory.getLogger(ExecteSqlLogInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        //捕获异常，不要影响业务
        Object returnValue = null;
        try {
            MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            Object parameter = null;
            if (invocation.getArgs().length > 1) {
                parameter = invocation.getArgs()[1];
            }
            BoundSql boundSql = mappedStatement.getBoundSql(parameter);
            Configuration configuration = mappedStatement.getConfiguration();
            String sqlId = mappedStatement.getId();
            int index = sqlId.indexOf("mapper");
            if (index != -1) {
                sqlId = sqlId.substring(index + 7);
            }
            long start = System.currentTimeMillis();

            returnValue = invocation.proceed();

            long end = System.currentTimeMillis();

            long time = end - start;
            if (time > 1) {
                String exexcSql = getSql(configuration, sqlId, time, boundSql);
                //System.out.println(exexcSql);
                daoLogger.info("===============\n"+exexcSql+"\n=============");
            }
            return returnValue;
        } catch (InvocationTargetException e) {
            return returnValue;
        } catch (IllegalAccessException e) {
            return returnValue;
        }
    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }

    private static String getRuntimeExeSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    }
                }
            }
        }
        return sql;
    }

    private static String getParameterValue(Object obj) {
        String value = "";
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(new Date()) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }
        }
        return value;
    }

    private String getSql(Configuration configuration, String sqlId, long time, BoundSql boundSql) {
        String sql = getRuntimeExeSql(configuration, boundSql);
        StringBuilder result = new StringBuilder();
        result.append(" [" + sqlId + "] ");
        result.append(" ==> \n");
        result.append(sql);
        result.append("\n ==> ");
        result.append(time);
        result.append("ms");
        return result.toString();
    }
}

